package com.notary.data.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.notary.config.TencentProperties;
import com.notary.data.service.OfficeRequestService;
import com.notary.entity.Contract;
import com.notary.entity.Custom;
import com.notary.entity.NotaryDocument;
import com.notary.entity.vo.JsonResult;
import com.notary.service.ContractService;
import com.notary.service.CustomService;
import com.notary.service.NotaryDocumentService;
import com.notary.util.DesUtil;
import com.notary.util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * <p>
 * 公证卷宗基本信息 前端控制器
 * </p>
 *
 * @author xujun
 * @since 2020-07-28
 */


@Api(tags = "api")
@RequestMapping("/api")
@RestController
@Slf4j
public class ReceiveDataController {


    OfficeRequestService officeRequestService;

    @Autowired
    public ReceiveDataController(OfficeRequestService officeRequestService) {
        this.officeRequestService = officeRequestService;
    }

    @Autowired
    CustomService customService;

    @Autowired
    private NotaryDocumentService notaryDocumentService;

    @Value("${office.deskey}")
    private String deskey;

    private static final String MEDIA_TYPE = "100";

    @Autowired
    TencentProperties tencentProperties;

    @Autowired
    private ContractService contractService;

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.bucketName}")
    private String bucketName;

    @Value("${aliyun.urlPrefix}")
    private String urlPrefix;

    @Value("${aliyun.folderName}")
    private String folderName;

    /**
     * <p>
     * 根据条件查询全部记录（并翻页）
     * </p>
     */

    @ApiOperation(value = "getOrderInfo")
    @PostMapping("/getOrderInfo")
    public JSONObject getOrderInfo(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.getOrderInfo(data);
    }


    @ApiOperation(value = "syncData")
    @PostMapping("/syncData")
    public JSONObject syncData(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.syncData(data);
    }


    @ApiOperation(value = "getNotaryInfo")
    @PostMapping("/getNotaryInfo")
    public JSONObject getNotaryInfo(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.getNotaryInfo(data);
    }


    @ApiOperation(value = "queryNotaryByTransNo")
    @PostMapping("/queryNotaryByTransNo")
    public JSONObject queryNotaryByTransNo(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.queryNotaryByTransNo(data);
    }


    @ApiOperation(value = "getNotaryStatus")
    @PostMapping("/getNotaryStatus")
    public JSONObject getNotaryStatus(@RequestBody JSONObject data) throws Exception {
        JSONObject jsonObject = officeRequestService.getNotaryStatus(data);
        return jsonObject;
    }

    @ApiOperation(value = "querySealNotaryPdf")
    @PostMapping("/querySealNotaryPdf")
    public byte[] querySealNotaryPdf(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.querySealNotaryPdf(data);
    }

    @ApiOperation(value = "queryPurpose")
    @PostMapping("/queryPurpose")
    public JSONObject queryPurpose(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.queryPurpose(data);
    }

    @ApiOperation(value = "queryNotaryItemInfo")
    @PostMapping("/queryNotaryItemInfo")
    public JSONObject queryNotaryItemInfo(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.queryNotaryItemInfo(data);
    }

    @ApiOperation(value = "获取公证处公证员相关信息")
    @PostMapping("/getNotaryIdAndName")
    public JSONObject getNotaryIdAndName(@RequestBody JSONObject data) throws Exception {
        return officeRequestService.getNotaryIdAndName(data);
    }


    @ApiOperation(value = "接收数据中心机构数据")
    @PostMapping("/saveCustom")
    public JsonResult saveCustom(@RequestBody JSONObject json) throws Exception {
        //log.info("接收数据中心机构数据:{}",json);
        //JSONObject json = JSONObject.parseObject(data);
        String string = DesUtil.decode(deskey, json.getString("timestamp"), json.getString("data"));
        log.info("接收数据中心机构数据:{}", string);
        JSONObject object = JSON.parseObject(string);
        Custom custom = JSONUtil.toBean(new cn.hutool.json.JSONObject(object), Custom.class);
        if (custom != null) {
            customService.save(custom);
            return JsonResult.success();
        } else {
            return JsonResult.fail();
        }
    }

    /**
     * 腾讯云实时音视频录制回调接口响应
     */
    @ApiOperation("腾讯云实时音视频录制回调接口响应")
    @PostMapping("/receiveTRTCVideoData")
    public JsonResult receive(@RequestBody Map<String, Object> mediaMap) {
        log.info("腾讯云回调返回参数：".concat(mediaMap.toString()));
        //获取签名
        String sign = mediaMap.get("sign").toString();
        //获取时间戳
        String time = mediaMap.get("t").toString();
        String md5 = MD5Utils.getMD5(tencentProperties.getSignKey() + time);
        if (!sign.equals(md5)) {
            return JsonResult.fail("该文件不是腾讯录制文件");
        }

        //消息类型，当 event_type 为100时，表示该回调消息为录制文件生成的消息。
        String eventType = mediaMap.get("event_type").toString();

        // 如果非录制文件消息就不处理
        if (!MEDIA_TYPE.equals(eventType)) {
            return JsonResult.fail("该文件不是录制文件");
        }
        String timetableId = mediaMap.get("stream_id").toString();
        String fileId = mediaMap.get("file_id").toString();

        String videoUrl = mediaMap.get("video_url").toString();
        String streamParam = mediaMap.get("stream_param").toString();

        String fileSize = mediaMap.get("file_size").toString();
        String fileFormat = mediaMap.get("file_format").toString();
        String startTime = mediaMap.get("start_time").toString();
        String endTime = mediaMap.get("end_time").toString();
        String[] paramsArray = streamParam.split("&");
        Map<String, String> map = new HashMap<>(paramsArray.length);
        for (String params : paramsArray) {
            String[] param = params.split("=");
            map.put(param[0], param[1]);
        }
        String userIdBase64 = map.get("userid");

        Base64.Decoder decoder = Base64.getDecoder();
        String lecturerId = null;
        InputStream inputStream = null;
        try {
            if (StringUtils.isNotBlank(userIdBase64)) {
                lecturerId = new String(decoder.decode(userIdBase64), "UTF-8");
                log.info("用户为：" + lecturerId);
                log.info("视频播放地址" + videoUrl);
                String[] split = lecturerId.split(",");
                //根据lecturerId查找是否存在该卷宗
                Contract contract = contractService.getById(split[0]);
                if (contract != null) {
                    URL url = new URL(videoUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    inputStream = conn.getInputStream();
                    String fileName = videoUrl.substring(videoUrl.lastIndexOf("/") + 1);
                    String key = folderName + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmss")) + "/" // 时间戳 文件目录
                            + UUID.randomUUID().toString().replaceAll("-", "") // uuid 生成文件名
                            + fileName.substring(fileName.lastIndexOf(".")); // 文件后缀
                    PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, inputStream);
                    log.info("上传结果为：" + putObjectResult.toString());
                    NotaryDocument notaryDocument = new NotaryDocument();
                    notaryDocument.setContractId(Long.valueOf(split[0]));
                    notaryDocument.setType(6);
                    if (split.length > 1) {
                        notaryDocument.setName("公证连线视频_公证员");
                    } else {
                        notaryDocument.setName("公证连线视频_当事人");
                    }
                    notaryDocument.setPath(urlPrefix + key);
                    notaryDocumentService.save(notaryDocument);
                } else {
                    return JsonResult.fail("该卷宗不存在！");
                }
            }
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error(e.toString());
            }
        }
        return JsonResult.success();
    }

    /**
     * 获取公证书存证哈希和执行证书存证哈希
     */
    @ApiOperation("获取公证书存证哈希和执行证书存证哈希")
    @PostMapping("/getNotaryOrExecuteHashCode")
    public JsonResult getNotaryOrExecuteHashCode(@RequestBody JSONObject data) {
        return officeRequestService.getNotaryOrExecuteHashCode(data);
    }
}

